require 'digest/sha1'

class User < ActiveRecord::Base

  has_and_belongs_to_many :works

  # Virtual attribute for the unencrypted password
  attr_accessor :password, :old_password

  validates_presence_of     :login, :email, :message => 'missing'
  validates_length_of       :email, :maximum => 50, :message => 'max'
  validates_length_of       :email, :minimum => 4, :message => 'min'
  validates_format_of       :login, :with => /^[0-9a-zA-Z.\-_]+$/, :message => 'format'
  validates_presence_of     :password,                   :if => :password_required? ,:message => 'missing'
  validates_presence_of     :password_confirmation,      :if => :password_required? ,:message => 'missing'
  validates_length_of       :password, :minimum => 4, :if => :password_required? ,:message => 'min'
  validates_length_of       :password, :maximum => 40, :if => :password_required? ,:message => 'max'
  validates_confirmation_of :password,                   :if => :password_required? ,:message => ''

  validates_length_of       :login, :minimum => 3, :message => 'min'
  validates_length_of       :login, :maximum => 40, :message => 'max'
  validates_format_of       :email, :with => /.+@.+\.[a-z.]+/, :message => 'format'

  validates_uniqueness_of   :login, :email, :case_sensitive => false , :message => 'unique'
  before_save :encrypt_password

  # prevents a user from submitting a crafted form that bypasses activation
  # anything else you want your user to change should be added here.
  attr_accessible :login, :email, :password, :password_confirmation, :old_password

  def has_attendee?
    Attendee.find(:all, :conditions => { :user_login => login } ).blank? ? false : true
  end

  def has_work?
    not @works.blank?
  end

  # Authenticates a user by their login name and unencrypted password.  Returns the user or nil.
  def self.authenticate(login, password)
    u = find_by_login(login) # need to get the salt
    u && u.authenticated?(password) ? u : nil
  end

  # Encrypts some data with the salt.
  def self.encrypt(password, salt)
    Digest::SHA1.hexdigest("--#{salt}--#{password}--")
  end

  # Encrypts the password with the user salt
  def encrypt(password)
    self.class.encrypt(password, salt)
  end

  def authenticated?(password)
    crypted_password == encrypt(password)
  end

  def remember_token?
    remember_token_expires_at && Time.now.utc < remember_token_expires_at
  end

  # These create and unset the fields required for remembering users between browser closes
  def remember_me
    remember_me_for 2.weeks
  end

  def remember_me_for(time)
    remember_me_until time.from_now.utc
  end

  def remember_me_until(time)
    self.remember_token_expires_at = time
    self.remember_token            = encrypt("#{email}--#{remember_token_expires_at}")
    save(false)
  end

  def forget_me
    self.remember_token_expires_at = nil
    self.remember_token            = nil
    save(false)
  end

  # Returns true if the user has just been activated.
  def recently_activated?
    @activated
  end

  def create_reset_code
    update_attribute(:reset, true)
    update_attribute (:reset_code ,Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join ))
    save!
  end

  def reset?
    read_attribute(:reset)
  end

  def delete_reset_code
    update_attribute(:reset, false)
    update_attribute(:reset_code, nil)
    save!
  end


  def send_reset_code
    Emailer.deliver_contact(email,"Código de recuperação de senha","Seu código é '#{reset_code}' . Clique <a href=\"www.sulpet2010.com.br/resetar\">neste</a> link para recuperar a sua senha.")
  end

  protected
    # before filter
    def encrypt_password
      return if password.blank?
      self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?
      self.crypted_password = encrypt(password)
    end

    def password_required?
      crypted_password.blank? || !password.blank?
    end


end

